<template>
  <div class='container'>
    <el-card>
      <!-- top -->
      <el-row type="flex" class="row-bg" justify="space-between">
        <el-col :span="18"><span class="info">说明：目前支持学科和关键字条件筛选</span>
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button type="success" icon="el-icon-edit" size="small" @click="toNew">新增试题
          </el-button>
        </el-col>
      </el-row>
      <!-- 用户填写表单 -->
      <el-form ref="questionsForm" :model="questionsForm" label-width="80px">
        <!-- 第一行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item size="small" label="学科" prop="subjectID">
              <el-select v-model="questionsForm.subjectID" placeholder="请选择" @change="subjectIDChange">
                <el-option v-for="item in simpleList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="二级目录" prop="catalogID">
              <el-select v-model="questionsForm.catalogID" placeholder="请选择">
                <el-option v-for="item in directorysList" :key="item.id" :label="item.directoryName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="标签" prop="tags">
              <el-select v-model="questionsForm.tags" placeholder="请选择">
                <el-option v-for="(item,index) in tagsList" :key="index" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="关键字" prop="keyword">
              <el-input v-model="questionsForm.keyword" placeholder="根据题干搜索"></el-input>
            </el-form-item>
          </el-col>
          <!-- 第二行 -->
          <el-col :span="6">
            <el-form-item size="small" label="试题类型" prop="questionType">
              <el-select v-model="questionsForm.questionType" placeholder="请选择">
                <el-option v-for="item in questionType" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="难度" prop="difficulty">
              <el-select v-model="questionsForm.difficulty" placeholder="请选择">
                <el-option v-for="item in difficulty" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="方向" prop="direction">
              <el-select v-model="questionsForm.direction" placeholder="请选择">
                <el-option v-for="(item,index) in direction" :key="index" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="录入人" prop="creatorID">
              <el-select v-model="questionsForm.creatorID" placeholder="请选择">
                <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 第三行 -->
          <el-col :span="6">
            <el-form-item size="small" label="题目备注" prop="remarks">
              <el-input v-model="questionsForm.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="企业简称" prop="shortName">
              <el-input v-model="questionsForm.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" label="城市" prop="province">
              <el-select v-model="questionsForm.province" placeholder="请选择" class="cityselect" @change="cityChange">
                <el-option v-for="(item,index) in provinces" :key="index" :label="item" :value="item">
                </el-option>
              </el-select>
              <el-select v-model="questionsForm.city" placeholder="请选择" style="width:50%;">
                <el-option v-for="(item,index) in citys" :key="index" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="small" class="right">
              <el-button size="small" @click="clearQuestionsForm">清除</el-button>
              <el-button type="primary" size="small" @click="search">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 警告框 -->
      <el-alert :title="`数据一共${counts}条`" type="info" show-icon :closable=false>
      </el-alert>
      <!-- 表格 -->
      <el-table :data="questionsList" stripe style="width: 100%">
        <el-table-column prop="number" label="试题编号" width="120">
        </el-table-column>
        <el-table-column prop="subject" label="学科">
        </el-table-column>
        <el-table-column prop="catalog" label="目录">
        </el-table-column>
        <el-table-column label="题型">
          <template v-slot="{row}">
            <span v-if="row.questionType==='1'">单选题</span>
            <span v-else-if="row.questionType==='2'">多选题</span>
            <span v-else>简答题</span>
          </template>
        </el-table-column>
        <el-table-column prop="question" label="题干" width="280">
          <template v-slot="{row}">
            <p v-html="row.question"></p>
          </template>
        </el-table-column>
        <el-table-column label="录入时间" width="180">
          <template v-slot="{row}">
            <span>{{row.addDate}}</span>
          </template>
        </el-table-column>
        <el-table-column label="难度">
          <template v-slot="{row}">
            <span v-if="row.difficulty==='1'">简单</span>
            <span v-if="row.difficulty==='2'">一般</span>
            <span v-if="row.difficulty==='3'">困难</span>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot="{row}">
            <!-- 点击预览 -->
            <el-button type="primary" icon="el-icon-view" circle plain size="small" @click="showDialog(row)">
            </el-button>
            <!-- 点击修改 -->
            <el-button type="success" icon="el-icon-edit" circle plain size="small" @click="goNew(row)"></el-button>
            <!-- 点击删除 -->
            <el-button type="danger" icon="el-icon-delete" circle plain size="small" @click="removeQuestion(row)">
            </el-button>
            <!-- 点击加入精选 -->
            <el-button type="warning" icon="el-icon-check" circle plain size="small" @click="addChoice(row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryinfo.page" :page-sizes="[1, 5, 10, 15]" :page-size="queryinfo.pagesize" :total="counts"
        layout=" prev, pager,next,sizes, jumper" background>
      </el-pagination>
    </el-card>
    <!-- 预览对话框组件 -->
    <preview-dialog :dialogVisible="previewDialogVisible" :rowData="rowData" @downDialog="downDialog"></preview-dialog>
  </div>
</template>

<script>
// 请求用户列表
import { list as userList } from '@/api/base/users.js'
// 去标签, 时间过滤器
import { html2Text, parseTime } from '@/filters'
// 请求基础题库列表 , 删除题库, 加精选, 详情列表
import { list, remove, choiceAdd, detail as questionsDetail } from '@/api/hmmm/questions.js'
// 请求学科下拉列表
import { simple } from '@/api/hmmm/subjects.js'
// 请求试题类型,难度,方向下拉列表
import { questionType, difficulty, direction } from '@/api/hmmm/constants.js'
// 请求城市,地区下拉列表
import { provinces, citys } from '@/api/hmmm/citys.js'
// 请求标签列表
import { list as tagsList } from '@/api/hmmm/tags.js'
// 选中学科请求二级目录列表
import { list as directorysList } from '@/api/hmmm/directorys.js'
// 题目预览对话框
import previewDialog from '@/module-hmmm/components/questions-previewjxk.vue'
export default {
  data () {
    return {
      questionsList: [], // 基础题库列表数据
      simpleList: [], // 学科数据
      directorysList: [], // 二级目录数据
      tagsList: [], // 标签列表
      questionType, // 试题类型
      difficulty, // 难度
      direction, // 方向
      userList: [], // 录入人
      citys: [], // 地区
      // 用户填写表单数据
      questionsForm: {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        province: ''
      },
      // 渲染列表参数
      queryinfo: {
        page: 1, // 当前页数
        pagesize: 5 // 一页展示数据条数
      },
      counts: 0, // 总条数
      // 预览对话框显隐
      previewDialogVisible: false,
      // 当前题库点击的数据 传给预览组件
      rowData: {}
    }
  },
  created () {
    // 学科数据
    this.getSimpleList()
    // 录入人
    this.getUserList()
    //  基础题库数据
    this.getQusetionsList()
  },
  methods: {
    // 基础题库表格修改跳转 => 试题录入
    goNew (row) {
      this.$router.push({ path: '/questions/new', query: { id: row.id } })
    },
    // 新增试题点击跳转 => 试题录入
    toNew () {
      this.$router.push('/questions/new')
    },
    // 学科数据
    async getSimpleList () {
      const res = await simple()
      console.log(res)
      this.simpleList = res.data
    },
    // 二级目录数据
    async getDetailList () {
      const res = await directorysList({ subjectID: this.questionsForm.subjectID })
      console.log(res)
      this.directorysList = res.data.items
    },
    // 标签数据
    async getTagsList () {
      const res = await tagsList({ subjectID: this.questionsForm.subjectID })
      console.log(res)
      const list = []
      res.data.items.forEach(item => {
        list.push(item.tagName)
      })
      this.tagsList = list
    },
    // 录入人
    async getUserList () {
      const res = await userList()
      this.userList = res.data.list
      console.log(res.data.list)
    },
    // 学科选择器改变
    subjectIDChange () {
      // 目录
      this.getDetailList()
      // 标签
      this.getTagsList()
    },
    // 城市选择改变
    cityChange (city) {
      this.citys = citys(city)
    },
    // 基础题库数据
    async getQusetionsList (data) {
      if (!data) {
        data = this.queryinfo
      }
      const res = await list(data)
      if (res.request.status !== 200) return this.$message.error('获取学科数据失败')
      res.data.items.forEach(async item => {
        // 题干处理 去标签
        item.question = html2Text(item.question)
        // 时间处理
        item.addDate = parseTime(new Date(item.addDate))
      })

      this.questionsList = res.data.items
      this.counts = res.data.counts
      this.queryinfo.page = res.data.page - 0
      this.queryinfo.pagesize = res.data.pagesize - 0
    },
    // 页码变化
    handleSizeChange (pagesize) {
      this.queryinfo.pagesize = pagesize
      this.getQusetionsList()
    },
    // 当前页变化
    handleCurrentChange (page) {
      this.queryinfo.page = page
      this.getQusetionsList()
    },
    // 点击清除
    clearQuestionsForm () {
      this.$refs.questionsForm.resetFields()
      this.getQusetionsList()
    },
    // 点击搜索
    search () {
      this.getQusetionsList(
        {
          ...this.queryinfo,
          keyword: this.questionsForm.keyword || null,
          subjectID: this.questionsForm.subjectID || null
        }
      )
    },
    // 基础题库点击删除
    removeQuestion (row) {
      console.log(row)
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // console.log(row)
        const res = await remove(row)
        console.log(res)
        if (res.request.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getQusetionsList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 基础题库点击加入精选
    addChoice (row) {
      this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async () => {
        const res = await choiceAdd({ id: row.id, choiceState: 1 })
        // console.log(res)
        if (res.request.status !== 200) return this.$message.error('加入精选失败')
        this.$message.success('加入精选成功')
        this.getQusetionsList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
      // console.log(row)
    },
    // 对话框
    // 点击对话框取消触发
    downDialog () {
      this.rowData = {}
      this.previewDialogVisible = false
    },
    // 点击预览显示对话框
    async showDialog (row) {
      this.previewDialogVisible = true
      const res = await questionsDetail({ id: row.id })
      console.log(res.data)
      // 题干处理 去标签
      res.data.question = html2Text(res.data.question)
      // 处理答案解析
      res.data.answer = html2Text(res.data.answer)
      // 预览对话框选项绑定默认值处理
      let isChoice = ''
      const isChoices = []
      if (res.data.questionType === '1') {
        res.data.options.forEach(item => {
          if (item.isRight === 1) {
            isChoice = item.code
          }
        })
      }
      if (res.data.questionType === '2') {
        res.data.options.forEach(item => {
          if (item.isRight === 1) {
            isChoices.push(item.code)
          }
        })
      }
      // 遍历options 为其item增加sortId属性 值为code的ASCII码转为数字
      res.data.options.forEach(item => {
        item.sortId = item.code.charCodeAt()
      })
      // console.log(res.data.options.sort(this.sortBy('sortId', true)))
      // 根据sortId 排序
      res.data.options.sort(this.sortBy('sortId', true))
      // 处理后的数据赋值到data里
      res.data.isChoice = isChoice
      res.data.isChoices = isChoices
      this.rowData = res.data
      console.log(this.rowData)
    },
    // 后台返回数据 选项顺序打乱bug  通过code的ASCII转数字升序排序
    sortBy (attr, rev) {
      // 第二个参数没有传递 默认升序排列
      if (rev === undefined) {
        rev = 1
      } else {
        rev = (rev) ? 1 : -1
      }
      return function (a, b) {
        a = a[attr]
        b = b[attr]
        if (a < b) {
          return rev * -1
        }
        if (a > b) {
          return rev * 1
        }
        return 0
      }
    }
  },
  computed: {
    provinces // 城市数据
  },
  components: {
    // 试题预览对话框
    previewDialog
  }
}
</script>

<style scoped lang='less'>
.el-card {
  margin: 10px;
}
.info {
  font-size: 12px;
  color: pink;
}
.el-form {
  margin-top: 10px;
}
.right {
  text-align: right;
}
.el-col {
  height: 51px;
}
.el-table {
  margin: 15px 0;
}
.el-pagination {
  text-align: right;
}
.el-select {
  width: 100%;
}
.cityselect {
  width: 48%;
  margin-right: 2%;
}
</style>
